package com.jiawei.service;

import com.jiawei.Interaction.WebSocketUtil;
import com.jiawei.exceptions.CustomException;
import com.jiawei.pojo.ParamConfig;
import com.jiawei.pojo.ResponseMsg;
import com.jiawei.utils.SerialPortUtils;
import org.springframework.stereotype.Service;

/**
 * @author : willian fu
 * @version : 1.0
 */
@Service
public class SerialPortServiceImpl implements SerialPortService{

   private static SerialPortUtils serialPort = new SerialPortUtils();

    public ResponseMsg open(ParamConfig paramConfig, String sessionId){
        try {
            WebSocketUtil.WsAndSerialPortMap.put(this.serialPort, sessionId);
            serialPort.init(paramConfig);
        } catch (CustomException e) {
            e.printStackTrace();
            return new ResponseMsg(400,"打开串口失败");
        }
        return new ResponseMsg(200,"打开串口成功");
    }


    public ResponseMsg close(){
        try {
            this.serialPort.closeSerialPort();
        } catch (CustomException e) {
            e.printStackTrace();
            return new ResponseMsg(400,"关闭串口异常");
        }
        return new ResponseMsg(200,"关闭串口成功");
    }

    public ResponseMsg send(String msg){
        try {
            this.serialPort.sendComm(msg);
        } catch (CustomException e) {
            e.printStackTrace();
            return new ResponseMsg(400,"发送失败");
        }
        return new ResponseMsg(204,"----------ok----------");
    }

    public ResponseMsg search(){
        return new ResponseMsg(201, this.serialPort.getAvailableSerialPortsName());
    }
}
